# main.py

import requests
import json
import time
import sys

keywords = {
    "keywords1": ["A股"],
    "keywords2": ["国能源部", "美国住房和城市发展部", "美国运输部", "美国国土安全部", "美国中央情报局", "美国联邦调查局", "美国环境保护署", "美国证券交易委员会", "美国消费者金"],
    "keywords3": [],
    "keywords4": [],
    "keywords5": ["欧洲中央银行", "欧洲审计院", "欧洲对外行动署"],
    "keywords6": [],
    "keywords7": ["控股股东", "实控人", "实际控制人", "控制权"]
}

# 获取最新消息的地址
base_url_new = 'http://zhibo.sina.com.cn/api/zhibo/feed?callback=jQuery0&page=1&page_size=1&zhibo_id=152&tag_id=0&dire=f&dpc=1&pagesize=1&_=0%20Request%20Method:GET'

# 自定义js提取页
def myurl(oldnum_str, thispagesize_str, oldpagesize_str):
    my_url_a = r'http://zhibo.sina.com.cn/api/zhibo/feed?callback=jQuery0&page='
    my_url_b = r'&page_size='
    my_url_c = r'&zhibo_id=152&tag_id=0&dire=f&dpc=1&pagesize='
    my_url_d = r'&_=0%20Request%20Method:GET'
    my_url = my_url_a + oldnum_str + my_url_b + thispagesize_str + my_url_c + oldpagesize_str + my_url_d
    return my_url

# 从js数据包中获得json数据
def get_json_str(base_url):
    json_str = ''
    try:
        response = requests.get(base_url, timeout=5)
        html = response.text
        html_cl = html[12:-14]
        html_json = eval(html_cl)
        json_str = json.dumps(html_json)
    except ConnectionError:
        print('get_json_str得到数据时网络连接有问题，未得到json数据')
    except UnboundLocalError:
        print('get_json_str您的电脑休眠导致连接中断')
    except Exception as errorname1:
        print('get_json_str未收录错误类型，请检查网络通断,错误位置：', errorname1)
    finally:
        return json_str

# json 数据解析函数
def json_str_analysis(json_date):
    date_dic = {}
    try:
        python_dic = json.loads(json_date)
        list_str = python_dic["result"]['data']['feed']['list']
        for list_dic in list_str:
            need_option = ['id', 'rich_text', 'create_time', 'tag']
            for listkey in list(list_dic.keys()):
                if listkey not in need_option:
                    list_dic.pop(listkey)
            date_dic[list_dic['id']] = list_dic
    except ValueError:
        print('json_str_analysis  json数据格式不对无法解析')
    except Exception as errorname2:
        print('json_str_analysis未知问题', errorname2)
    finally:
        return date_dic

# 显示解析后的数据
def list_dic_display(listdic):
    create_timez_str = tag_id_str = type_str = rich_text_str = data_id_str = ''
    data_id_str = listdic['id']
    rich_text_str = listdic['rich_text']
    create_timez_str = listdic['create_time']
    tag_str = listdic['tag']

    tag_id_str = []
    type_str = []
    for tag_dic in tag_str:
        tag_id_str.append(tag_dic['id'])
        type_str.append(tag_dic['name'])

    print(r'时间:', create_timez_str)
    print(r'内容:', rich_text_str)

# 发送消息到指定URL
def send_message(url, create_timez_str, rich_text_str):
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": f"【时间】：{create_timez_str}，【内容】：{rich_text_str}"
        }
    }
    response = requests.post(url=url, data=json.dumps(data), headers=headers)
    return response

# 检查关键词并发送消息到相应的URL
def check_keywords_and_send(listdic, create_timez_str):
    rich_text_str = listdic.get('rich_text', '')

    if not any(keyword in rich_text_str for keyword in keywords['keywords1']):
        print("未检测到关键词1")
        if sum(1 for keyword in keywords['keywords2'] if keyword in rich_text_str) < 2:
            print("未检测到关键词2")
            if any(keyword in rich_text_str for keyword in keywords['keywords3']):
                print("检测到关键词3")
                url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b13c34b8-0461-48b1-8603-fd33dbf88618"
            elif '变更' in rich_text_str and any(keyword in rich_text_str for keyword in keywords['keywords7']):
                print("检测到关键词7和变更")
                url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3d22cac4-cf80-4af5-8abb-96aa35475124"
            elif any(keyword in rich_text_str for keyword in keywords['keywords6']):
                print("检测到关键词6")
                url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4376f736-0459-4114-b1e6-6523f0a8517c"
            elif any(keyword in rich_text_str for keyword in keywords['keywords5']) and not any(keyword in rich_text_str for keyword in keywords['keywords4']):
                print("检测到关键词5且未检测到关键词4")
                url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d434234f-de01-4aad-a00f-3e7c3a262180"
            else:
                print("未检测到任何关键词")
                url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=dde9e8fb-9138-4bee-8a37-2100560ec7a0"

            send_message(url, create_timez_str, rich_text_str)
        else:
            print("检测到关键词2")
    else:
        print("检测到关键词1")

# 主函数
def post_url(listdic, create_timez_str):
    print("---" * 2)
    print("ok")
    print("---" * 2)
    check_keywords_and_send(listdic, create_timez_str)
    return listdic.get('rich_text', '')

if __name__ == '__main__':
    lastdateid = '0'
    i = 1
    n = 1

    while True:
        json_date = get_json_str(base_url_new)
        if json_date:
            jsaoutput_dic = json_str_analysis(json_date)
            if jsaoutput_dic:
                for dataid in jsaoutput_dic.keys():
                    if int(dataid) <= int(lastdateid):
                        print('此次刷新没有获得数据，等待5s后将继续刷新', n)
                        time.sleep(5)
                        n += 1
                    else:
                        try:
                            richtextstr = list_dic_display(jsaoutput_dic[dataid])
                            post_url(jsaoutput_dic[dataid], jsaoutput_dic[dataid]['create_time'])
                            i += 1
                            n = 0
                            lastdateid = dataid
                            time.sleep(5)
                        except ValueError:
                            print('main处理数据错误')
                        except Exception as errorname3:
                            print(errorname3)
            else:
                print('jsa_flag为0，json_str_analysis解析数据失败')
                print('等待5s后将继续刷新')
                time.sleep(5)
        else:
            print('get_json_flag为0，get_json_str未能得到json数据')
            print('等待5s后将继续刷新')
            time.sleep(5)
